// 把这个注入到background
// 开发环境可以直接import进去，这里在window上定义变量，会覆盖background.js上的window变量
// 开发环境可以自己模拟指令
class Bg {

    bgVersion = '0.0.1';

    constructor() {
        this.contentScriptCacheInit()
    }

    /** 判断是否是非法页面 */
    IsIllegalPages = (url = '') => {
        const illegal = [
            'chrome://',
            'edge://',
            'about:',
            'moz-extension://',
            'res://',
            'view-source:',
            'devtools://',
            'https://ntp.msn.cn',
            'https://devtools.azureedge.net',
            'chrome-extension://',
        ];
        const flag = illegal.every((str) => !url.startsWith(str));
        return !flag;
    }

    getCurrentTab = async () => {
        const queryOptions = { active: true };
        const [tab] = await chrome.tabs.query(queryOptions);
        return tab;
    }

    // 页面注入contentScript
    contentScriptCacheInit = async () => {
        // 将window._F注入到所有页签中，注入的func会立即执行
        chrome.tabs.query({}, (tabs) => {
            tabs.forEach(async (tab) => {
                try {
                    if (tab.status === 'complete' && !this.IsIllegalPages(tab.url)) {

                        const isInjected = await chrome.scripting
                            .executeScript({
                                target: { tabId: tab.id },
                                func: () => {
                                    console.log(window.co)
                                    return !!window.co
                                },
                                args: []
                            })
                        if (!isInjected[0].result) {
                            const contentScriptCache = window.pluginBg.contentScriptCache;
                            const { func } = await window.pluginBg.generateFunc(contentScriptCache);
                            await chrome.scripting
                                .executeScript({
                                    target: { tabId: tab.id, allFrames: true },
                                    func,
                                    args: []
                                })
                        }
                    }
                } catch (error) {
                    console.error(error)
                }
            });
        });

        // 更新注入，注入的func会立即执行
        chrome.webNavigation.onCompleted.addListener(async (details) => {
            console.log('onCompleted')
            try {
                const { tabId, url } = details;
                if (!this.IsIllegalPages(url)) {
                    const contentScriptCache = window.pluginBg.contentScriptCache;
                    const { func } = await window.generateFunc(contentScriptCache);
                    await chrome.scripting
                        .executeScript({
                            target: { tabId: tabId, allFrames: true },
                            func
                        })
                }
            } catch (error) {
                console.error(error)
            }
        });
    }

    getRect = async () => {
        const tab = await this.getCurrentTab();
        console.log(tab, 'tab')
        if (!tab) return

        const res = await chrome.scripting
            .executeScript({
                target: { tabId: Number(tab.id) },
                func: async (action) => {
                    const res = await window.co.invoke(action);
                    console.log(res);
                    return {
                        status: 'success',
                        result: typeof res === 'string' ? res : JSON.stringify(res)
                    };
                },
                args: [{
                    type: 'getRect',
                    payload: {
                        xpath: '//body'
                    }
                }]
            })
        console.log(res, '000000000000')
    }
}

window.bg = new Bg();